import uvicorn
from fastapi import FastAPI, Depends, HTTPException, APIRouter,Query
from fastapi.responses import JSONResponse,HTMLResponse
from pydantic import BaseModel
from typing import List
from models import ChatModel
from tortoise.contrib.fastapi import register_tortoise
from settings import TORTOISE_ORM
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)
class Chat(BaseModel):
    from_user: str
    content: str
    # ctime: str  # 或者使用 datetime 类型


# 路由
# @app.get("/chat/send/")
# async def send_chat(chat: Chat):
#     print(chat)
#     await ChatModel.create(from_user=chat.from_user, content=chat.content)
#     return JSONResponse(content={'code': 100, 'msg': '发送成功'}, headers={'Access-Control-Allow-Origin': '*'})
@app.get("/chat/send/")
async def send_chat(from_user: str = Query(...), content: str = Query(...)):
    chat = Chat(from_user=from_user, content=content)  # 创建Chat实例
    print(chat)
    await ChatModel.create(from_user=chat.from_user, content=chat.content)
    return JSONResponse(content={'code': 100, 'msg': '发送成功'}, headers={'Access-Control-Allow-Origin': '*'})


@app.get("/chat/")
async def list_chats():
    """Retrieve a list of chats from the database."""

    chats = await ChatModel.all()
    result = []
    for chat in chats:


        d = {'from_user': chat.from_user, 'content': chat.content, 'ctime': chat.ctime.strftime("%Y-%m-%d %H:%M:%S")}
        print(d)
        result.append(d)
    return {'data':{'code': 100, 'msg': '查询成功', 'results': result}}


# fastapi一旦运行，register_tortoise已经执行，实现监控
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
)

if __name__ == '__main__':
    uvicorn.run('main:app', host='127.0.0.1', port=8010, reload=True, workers=1)
